
import 'package:flutter/material.dart';
import 'package:ycbl/config/bl_style.dart';
import 'package:ycbl/utils/log_util.dart';

/// dialog 是否正在显示
bool _isShowing = false;
/// context
BuildContext _context, _dismissingContext;
/// 点击 dialog 外部是否可消失
bool _barrierDismissible = true;
/// 提示文字
String _text;
/// dialog 显示的布局
DialogBody _body;
/// 加载中...
const _DEFAULT_TEXT = '加载中...';

/// 加载中 Dialog
class BLLoadingDialog{

  BLLoadingDialog(BuildContext context, {bool isDismissible,}) {
    _context = context;
    _barrierDismissible = isDismissible ?? true;
  }

  bool isShowing() => _isShowing;

  /// 显示 Dialog
  show({String text = _DEFAULT_TEXT}) {

    try {
      if (!_isShowing) {
        //LogUtil.d('show dialog');
        //设置提示文字
        _setText(text);
        //要显示的布局内容
        _body = DialogBody();
        // 调用 showDialog 显示 Dialog
        showDialog(
          context: _context,
          barrierColor: Colors.black26, // 半透明区域颜色
          barrierDismissible: _barrierDismissible, // 点击 半透明区域是否可以消失
          builder: (context) {
            //取消对话框时用到的 context
            _dismissingContext = context;
            return WillPopScope( // 使用  WillPopScope 控制点击返回按钮是否消失
              onWillPop: () async => _barrierDismissible,
              child: _body,
            );
          }
        );

        _isShowing = true;
      }else {
        //判断文字是否发生变化，变化则更新布局
        bool needUpdate = _text != text;
        //LogUtil.d('dialog is already showing needUpdate: $needUpdate');
        if(needUpdate) {
          //设置提示文字
          _setText(text);
          //更新
          _body?.update();
        }
      }

    }catch (e) {
      _isShowing = false;
      LogUtil.e('show dialog error：$e');
    }
  }

  /// 内部调用，赋值
  _setText(String text) {
    _text = text ?? _DEFAULT_TEXT;
  }

  /// 隐藏 Dialog
  dismiss() {
    try{
      //LogUtil.d('dismiss dialog');
      if(_isShowing && _dismissingContext != null) {
        _isShowing = false;
        Navigator.of(_dismissingContext).pop();
      }
    }catch (e) {
      LogUtil.e('hide dialog error：$e');
    }
  }

}

/// 加载中 Dialog 布局
class DialogBody extends StatefulWidget {

  final _DialogBodyState _bodyState = _DialogBodyState();

  update() {
    _bodyState.update();
  }

  @override
  _DialogBodyState createState() => _bodyState;
}

class _DialogBodyState extends State<DialogBody> {

  /// 更新显示文字
  update() {
    setState(() {});
  }

  @override
  void dispose() {
    _isShowing = false;
    //LogUtil.d('Dialog dismissed by pop or touch outside');
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return  MediaQuery.removeViewInsets(
      removeLeft: true,
      removeTop: true,
      removeRight: true,
      removeBottom: true,
      context: context,
      child: Center(
        child: Material(
          // 背景色
          color: Colors.white,
          // 影深
          elevation: 5,
          // 形状
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(8),
          ),
          type: MaterialType.card,
          clipBehavior: Clip.antiAlias,
          child: Container(
            // 内容边距 如果文字为空，则呈现为正方形，否则呈现为长方形
            padding: _text == '' ? EdgeInsets.all(20) : EdgeInsets.fromLTRB(20, 16, 20, 16),
            // 行排列：左侧进度指示器， 右侧加载中文字
            child: Row(
              // 包裹内容
              mainAxisSize: MainAxisSize.min,
              children: [
                SizedBox(
                  width: 30,
                  height: 30,
                  child: CircularProgressIndicator(
                    // 背景色
                    backgroundColor: Colors.grey.withAlpha(50),
                    // 进度颜色
                    valueColor: AlwaysStoppedAnimation(Colors.orange),
                    // 线宽
                    strokeWidth: 3,
                  ),
                ),

                // 如果文字为空，则文字和进度之间没有边距
                SizedBox(width: _text == '' ? 0 : 16,),

                Text(_text, style: BLStyle.middleTextStyle,)
              ],
            ),
          ),
        ),
      ),
    );
  }
}
